package com.microservice.common.interceptor;

import com.microservice.api.common.Result;
import com.microservice.api.auth.AuthServiceClient;
import com.microservice.common.context.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;



/**
 * Token验证拦截器
 * 自动验证Token并将用户信息存入UserContext
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {
    
    @Autowired
    private AuthServiceClient authServiceClient;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取Token
        String token = request.getHeader("Authorization");
        
        if (token == null || token.isEmpty()) {
            log.warn("请求未携带Token，路径：{}", request.getRequestURI());
            writeErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "未授权：缺少Token");
            return false;
        }
        
        // 调用认证服务验证Token
        try {
            Result<Boolean> result = authServiceClient.validateToken(token);
            if (result.getCode() == 200 && Boolean.TRUE.equals(result.getData())) {
                // Token有效，获取用户信息并存入UserContext
                Result<Long> userIdResult = authServiceClient.getUserIdFromToken(token);
                Result<String> usernameResult = authServiceClient.getUsernameFromToken(token);
                Result<String> nickNameResult = authServiceClient.getNicknameFromToken(token);

                if (userIdResult.getCode() == 200 && usernameResult.getCode() == 200) {
                    // 设置到UserContext（推荐方式）
                    UserContext.setUser(userIdResult.getData(), usernameResult.getData(),nickNameResult.getData());
                    
                    // 同时设置到request attribute（兼容旧方式）
                    request.setAttribute("userId", userIdResult.getData());
                    request.setAttribute("username", usernameResult.getData());
                    
                    log.debug("用户 {} (ID:{}) 通过Token验证", usernameResult.getData(), userIdResult.getData());
                }
                
                return true;
            } else {
                log.warn("Token验证失败，路径：{}", request.getRequestURI());
                writeErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "未授权：Token无效或已过期");
                return false;
            }
        } catch (Exception e) {
            log.error("Token验证异常，路径：{}，异常信息：{}", request.getRequestURI(), e.getMessage(), e);
            writeErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器错误：" + e.getMessage());
            return false;
        }
    }
    
    /**
     * 写入错误响应
     * 统一处理响应格式，确保客户端能正确接收
     */
    private void writeErrorResponse(HttpServletResponse response, int status, String message) throws Exception {
        response.setStatus(status);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        // 添加CORS头，防止跨域问题导致响应无法读取
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        
        String jsonResponse = String.format("{\"code\":%d,\"message\":\"%s\",\"data\":null}", status, message);
        response.getWriter().write(jsonResponse);
        response.getWriter().flush();
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后清除UserContext，防止内存泄漏
        UserContext.clear();
    }
}
